<?php

// See if we need to create SQL tables
$db =& JFactory::getDBO();
$table_list = $db->getTableList();
$table_prefix = $db->getPrefix();
$path=JPATH_BASE;
$path=str_replace('administrator', 'config', $path);
JFolder::create($path,0755);
$path=str_replace('config', 'includes', $path);
JFile::move('defines.php', 'defines.php.ORIG', $path);
JFile::move('framework.php', 'framework.php.ORIG', $path);
JFile::move(JPATH_BASE.'/components/com_multisite/defines.php', $path.'/defines.php');
JFile::move(JPATH_BASE.'/components/com_multisite/framework.php', $path.'/framework.php');
$path2=JPATH_BASE;
$path2=$path2.'/includes';

// Patch defines and framework
JFile::move('defines.php', 'defines.php.ORIG', $path2);
JFile::move('framework.php', 'framework.php.ORIG', $path2);
JFile::move(JPATH_BASE.'/components/com_multisite/definesadmin.php', $path2.'/defines.php');
JFile::move(JPATH_BASE.'/components/com_multisite/frameworkadmin.php', $path2.'/framework.php');


// Create the multisite table if it does not exist already
if (array_search($table_prefix . 'multisite',$table_list) == false) {
	$query = 'CREATE TABLE `#__multisite` (
	  `id` int(11) NOT NULL auto_increment,
	  `name` varchar(25) NOT NULL,
	  `url` varchar(128) NOT NULL,
	  `prefix` varchar(128) NOT NULL,
	  PRIMARY KEY  (`id`)
	)  DEFAULT CHARACTER SET utf8;';

	$db->setQuery($query);
	if (!$db->query()){
		echo $db->stderr() . '<br/>';
	}
	
	// Add the default entry for this table
	$entry = new stdClass;
	$entry->url = JURI::root();
	$entry->name = 'Main Site';
	$entry->prefix = $table_prefix;
    if (!$db->insertObject('#__multisite', $entry)) {
    	// Return the error
		echo $db->stderr() . '<br/>';
    }	
}